using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using System.Security;
using agsXMPP.protocol.client;

namespace PoshXmpp
{
    [Cmdlet(VerbsCommunications.Receive, "Message", SupportsShouldProcess = false)]
    public class ReceiveMessageCommand : XmppCommandBase
    {

        #region Parameters
        [Parameter(
        Mandatory = false,
        HelpMessage = "Show all available messages")]
        public SwitchParameter All { get; set; }

        [Parameter(
        Mandatory = false,
        HelpMessage = "Show all available messages, and loop waiting for more")]
        public SwitchParameter Loop { get; set; }

        [Parameter(
        Mandatory = false,
        HelpMessage = "Format the output for you")]
        public SwitchParameter Format { get; set; }
        #endregion

        protected override void BeginProcessing()
        {
            if(Loop.IsPresent) {
                All = Loop;
            }
            
            base.BeginProcessing();
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            do
            {
                foreach (Message m in Client.Messages)
                {
                    if (Format || Loop)
                    {
                        if (Client.ChatManager.IsInRoom(m.From))
                        {
                            WriteObject(string.Format("{2}<{0}> {1}", m.From.Resource, m.Body, m.From.User));
                        }
                        else
                        {
                            WriteObject(string.Format("<{0}> {1}", m.From.Bare, m.Body));
                        }
                    } else {
                        WriteObject(m); // TODO: create type format files
                    }
                    // if not "All" then we only process one message
                    if (!All.ToBool()) { break; }
                }
                if (Loop.ToBool())
                {
                    System.Threading.Thread.Sleep(0);
                }
            } while (Loop.ToBool() && !Host.UI.RawUI.KeyAvailable);
        }
    }
}
